import { Component, OnInit } from '@angular/core';
import { AutoUnsubscribe } from 'ngx-auto-unsubscribe-decorator';
import { DemoAction, DemoSelector } from '../../store/demo';
import { FormBuilder, FormGroup, UntypedFormControl, ValidationErrors, Validators } from '@angular/forms';
import { Store } from '@ngxs/store';
import { OverlayRef } from '@angular/cdk/overlay';
import { Observable, Observer } from 'rxjs';
import * as _ from 'lodash';

@Component({
  selector: 'app-menu-edit',
  templateUrl: './menu-edit.component.html',
  styleUrls: ['./menu-edit.component.scss'],
})
export class MenuEditComponent implements OnInit {
  @AutoUnsubscribe() menuEditType$ = this.store.select(DemoSelector.menuEditType);
  validateForm: FormGroup;

  constructor(
      private store: Store,
      private overlayRef: OverlayRef,
      private fb: FormBuilder,
  ) {
    this.validateForm = this.fb.group({
      id: [null],
      name: ['', [Validators.required]],
      code: ['', [Validators.required], [this.codeAsyncValidator]],
    });
  }

  ngOnInit(): void {
    this.store.select(DemoSelector.menuEditFlag).subscribe(r => {
      if (!r)
        this.overlayRef.dispose();
    });
  }

  codeAsyncValidator = (control: UntypedFormControl) => new Observable((observer: Observer<ValidationErrors | null>) => {
    let menuCodeList = this.store.selectSnapshot(DemoSelector.menuCodeList);
    let obj = _.find(menuCodeList, s => s.code === control.value && s.id !== this.validateForm.getRawValue().id);
    if (!!obj) {
      observer.next({error: true, duplicated: true});
    } else {
      observer.next(null);
    }
    observer.complete();
  });

  close() {
    this.store.dispatch(new DemoAction.CloseMenu());
  }

  submit() {
    this.store.dispatch(new DemoAction.SaveMenu());
  }
}
